package com.miss.spjyx.utils

import android.content.Context
import android.media.AudioManager
import android.media.SoundPool
import android.os.SystemClock
import com.miss.spjyx.CkApp
import com.miss.spjyx.R
import java.util.HashMap

/**
 * Sound utils
 *
 * @author wl
 * @since 2019/08/31 20:38
 */
object SoundUtils {
    private var sp: SoundPool = SoundPool(1, AudioManager.STREAM_MUSIC, 1)
    private var soundMap: MutableMap<Int, Int> = HashMap()

    //初始化声音池
    init {
        soundMap[1] = sp.load(CkApp.app, R.raw.msg0, 1)
    }

    var soundfinished: Boolean = false
    //播放声音池声音
    fun play(sound: Int, number: Int) {
        soundfinished = true
        val am = CkApp.app.getSystemService(Context.AUDIO_SERVICE) as AudioManager
        //返回当前AlarmManager最大音量
        val audioMaxVolume = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC).toFloat()

        //返回当前AudioManager对象的音量值
        val audioCurrentVolume = am.getStreamVolume(AudioManager.STREAM_MUSIC).toFloat()
        val volumnRatio = audioCurrentVolume / audioMaxVolume
        sp.play(
            soundMap[sound]!!, //播放的音乐Id
            audioCurrentVolume, //左声道音量
            audioCurrentVolume, //右声道音量
            1, //优先级，0为最低
            number, //循环次数，0无不循环，-1无永远循环
            1f
        )//回放速度，值在0.5-2.0之间，1为正常速度
        SystemClock.sleep(200)
        soundfinished = false
    }
}